package com.zhou.nio.client;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Date;
import java.util.Scanner;

/**
 * @descrition: UDP
 * @author: zhouyongjun
 * @date: 2022/8/29
 **/
@Slf4j
public class UDPDatagramChannelClient {
    static class Client{
        int id;
        DatagramChannel channel;
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        Client(int id) throws IOException {
            this.id = id;
            channel = DatagramChannel.open();
            channel.configureBlocking(false);
        }
        void send(String msg) throws IOException {
            buffer.put((new Date().toString()+">>>编号:"+id+">>>"+msg).getBytes());
            buffer.flip();
            channel.send(buffer,new InetSocketAddress("127.0.0.1",18080));
            buffer.clear();
        }

        public void close() throws IOException {
            channel.close();
        }
    }
    public static void main(String[] args) throws IOException {
        startClient();
    }

    private static void startClient() throws IOException {

        Client[] clients = {
                new Client(1),
                new Client(2),
                new Client(3),
        };

        Scanner scanner = new Scanner(System.in);
        log.debug("UDP客户端启动成功！");
        log.info("请输入发送内容：");
        int i =  -1;
        while (scanner.hasNext()) {
            i++;
            if (i >= clients.length ) {
                i = 0;
            }
            clients[i].send(scanner.next());
        }
        for (int i1 = 0; i1 < clients.length; i1++) {
            clients[i1].close();
        }
    }
}
